package apkinser

import (
    "log"
    "fmt"
    "bytes"
    "strings"
    "os/exec"
)

func Install(apkpath string) string {
    shellPath, err := exec.LookPath("sh")
    if err != nil {
        log.Println("installing sh is in your future")
        return "-1"
    }
    fmt.Printf("sh is available at %s\n", shellPath)

    pmPath, err := exec.LookPath("pm")
    if err != nil {
        log.Println("installing pm is in your future")
        return "-1"
    }
    fmt.Printf("pm is available at %s\n", pmPath)

    cmd := exec.Command(shellPath, pmPath, "install", "-r", apkpath)
    //cmd := exec.Command(shellPath, pmPath, "install", apkpath)
    var out bytes.Buffer
    var eout bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &eout
    err = cmd.Run()
    if err != nil || (eout.Len() != 0 && strings.Contains(eout.String(), "Failure")) {
        if (err != nil) {
            log.Println("Install Exec Error:", err.Error())
        }
        log.Println("Install Error:", eout.String())
        return "-1"
    }
    fmt.Printf("Install Success: %s", out.String())
    return "0"
}

// $ dumpsys iphonesubinfo
// Phone Subscriber Info:
//  Phone Type = GSM
//  Device ID = null
func GetImei() string {
    out,err := exec.Command("dumpsys", "iphonesubinfo").Output()
    if err != nil || len(out) <= 0 {
        return "1234567890ABCDE"
    }

    infos := strings.Split(string(out), "= ")
    return strings.Replace(infos[len(infos) - 1], "\n", "", 1)
}
